﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using Microsoft.Practices.EnterpriseLibrary.Caching;
using Microsoft.Practices.EnterpriseLibrary.Caching.Expirations;
using YXQ.Common.Helper;
using YXQ.Dao;
using YXQ.Dao.ViewModel;
using System.Web.Security;

namespace YXQ.Service
{
  public static  class MembershipService
    {
      /// <summary>
      /// 验证用户
      /// </summary>
      /// <param name="uname"></param>
      /// <param name="pwd"></param>
      /// <param name="tpid"></param>
      /// <returns></returns>
      public static bool ValidateUser(string uname,string pwd,int tpid) {

          using (YXQManageEntities edm = new YXQManageEntities()) {

              var upwd = StringUtils.EncryptPassWord(pwd, StringUtils.PassFormat.MD5);


              var umd = edm.Y_User.FirstOrDefault(s => s.UserName == uname && s.Pwd == upwd&&s.Status==0);
              if (umd == null)
              {
                  return false;
              }
              else {
                  FormsAuthentication.SetAuthCookie(umd.UserName,true);
                  return true;
              }
          } 
           
        }


        public static string GenerateName(string uname)
        {
            return uname + "@";
        }


        /// <summary>
        /// 刷新缓存用户
        /// </summary>
        /// <param name="uname"></param>
        /// <returns></returns>
        public static UserModel FlushUser(string uname)
        {
            ICacheManager userCache = CacheFactory.GetCacheManager();
            string UsCacheID = GenerateName(uname) + "@U";

            if (userCache.Contains(UsCacheID))
                userCache.Remove(UsCacheID);

            return GetUser(uname);
        }
        /// <summary>
        /// 获取用户
        /// </summary>
        /// <returns></returns>
        public static UserModel GetUser()
        {
            return GetAdminUser();

        }
        private static UserModel GetAdminUser()
        {
            string[] userName = GetSplitLogName();
            if (userName.Length >= 1)
            {
                return GetUser(userName[0] == "" ? "" : userName[0]);
            }
            else
            {
                return null;
            }
        }


        private static string[] GetSplitLogName()
        {
         // var uid=  Membership.GetUser().ProviderUserKey;
            string[] userName = HttpContext.Current.User.Identity.Name.Split('@');
            return userName;
        }


        public static UserModel GetUser(string username)
        {
            ICacheManager userCache = CacheFactory.GetCacheManager();
            string UsCacheID = MembershipService.GenerateName(username) + "@U";
            UserModel user = userCache.GetData(UsCacheID) as UserModel;
            if (user == null)
            {
                using (YXQManageEntities edm = new YXQManageEntities())
                {

                    IQueryable<UserModel> admModel = null;
                    
                    admModel = from s in edm.Y_User 
                                where s.UserName == username
                                select new UserModel()
                                {
                                    CreateTime = s.CreateTime, 
                                    Id = s.Id, 
                                    UserName = s.UserName,
                                    Pwd=s.Pwd,
                                    RealName=s.RealName,
                                    LastLoginTime=s.LastLoginTime,
                                    ThisLoginTime=s.ThisLoginTime,
                                    LoginCount=s.LoginCount,
                                    Status=s.Status,
                                    Email = s.Email,
                                     

                                };
                    user = admModel.FirstOrDefault();
                    if (user != null)
                    {
                        user.LoginCount = user.LoginCount == null ? 0 : user.LoginCount + 1;
                        user.LastLoginTime = user.ThisLoginTime;
                        user.ThisLoginTime = DateTime.Now;
                       

                        var um = from s in edm.Y_UM
                                    where s.UserId == user.Id
                                    select s;
                        if (um.FirstOrDefault()!= null) {
                            user.UserSysRight = um.FirstOrDefault().MudleId;
                            user.Depart = um.FirstOrDefault().DepartId;
                        }
                    }

                    if (user != null)
                    {
                        CenterService.userService.Save(user);
                    }

                    if (user != null)
                    {
                      
                        userCache.Add(UsCacheID, user, CacheItemPriority.High, null, new SlidingTime(TimeSpan.FromMinutes(180)));

                    }
                    //var query = edm.E_AdminUser.Where(s => s.UserName == username);

                }
               
            }
            return user;
        }
    }
}
